package com.tao.task;

import com.tao.mapper.OrderMapper;
import com.tao.pojo.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component//交给spring容器进行管理
@Slf4j
//一个定时任务类可以有多个定时方法
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;


    @Scheduled(cron = "0 * * * * *")//通过ai生成springtask框架下的cron表达式
    public void processTimeOutOrder(){
        log.info("{}处理超时订单", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Order> orders = orderMapper.selectByTime(time,Order.PENDING_PAYMENT);
        log.info("超时未处理的订单有:{}",orders);


        orders.forEach(order -> {
            order.setStatus(Order.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("订单支付超时");
            orderMapper.updateOrder(order);
        });
        log.info("超时订单处理完毕");
    }

    @Scheduled(cron = "0 0 1 * * ?")//ai生成springtask框架下每天凌晨1点触发一次的cron表达式
    public void processDeliveryOrder(){
        log.info("{}派送异常订单处理", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusWeeks(3);//将派送三周定义为异常
        List<Order> orders = orderMapper.selectByTime(time,Order.DELIVERY_IN_PROGRESS);

        log.info("派送异常的订单有:{}",orders);

        orders.forEach(order -> {
            order.setStatus(Order.COMPLETED);//自动修改为完成
            orderMapper.updateOrder(order);
        });
        log.info("派送异常订单处理完毕");
    }
}
